﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartConference.ErrorCode;
using System.IO;

namespace SmartConference.Api.Controllers
{
    /// <summary>
    /// 上传文件
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "会议管理")]
    public class UploadController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IWebHostEnvironment env;

        public UploadController(IConfiguration configuration,IWebHostEnvironment env)
        {
            this.configuration = configuration;
            this.env = env;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> UploadImage(IFormFile formFile)
        {
            try
            {
                //文件大小
                var fileSize = formFile.Length / 1024 / 1024;
                if (fileSize > Convert.ToInt64(configuration["UploadConfig:Limit"]))
                {
                    return ApiResult<string>.Error(ApiResultCode.Fail, "文件大小超出限制");
                }
                //文件后缀
                var fileExt = Path.GetExtension(formFile.FileName).ToLower();
                if (!configuration["UploadConfig:ExtName"].Split(',').Any(x=>x==fileExt.Trim('.')))
                {
                    return ApiResult<string>.Error(ApiResultCode.Fail, "文件格式错误");
                }
                Directory.CreateDirectory($"{env.WebRootPath}/Uploads/images/{DateTime.Now.ToString("yyyyMMdd")}");
                var newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-{Random.Shared.Next(1000, 9999)}{fileExt}";
                var filepath = $"{env.WebRootPath}/Uploads/images/{DateTime.Now.ToString("yyyyMMdd")}/{newFileName}";
                using (var stream = new FileStream(filepath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
                return ApiResult<string>.Success(ApiResultCode.Success, $"/Uploads/images/{DateTime.Now.ToString("yyyyMMdd")}/{newFileName}");
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
